//
//  NotificationViewController.m
//  Comma
//
//  Created by dlios on 15-1-14.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "LoginAndRegisterViewController.h"
#import "NotificationViewController.h"
#import "NotificationView.h"
#import "AFNetWorkingYU.h"
#import "GlobalMacro.h"
#import "GlobalMethod.h"
#import "URLMacro.h"
#import "DetailModel.h"
#import "UIImageView+WebCache.h"
#import "NotificationTableViewCell.h"
#import "DetailViewController.h"
#import "YRSideViewController.h"
#import "MJRefresh.h"
#import "MJRefreshHeaderView.h"
#import "MJRefreshFooterView.h"
#import "OtherModel.h"
#import "Reachability.h"
@interface NotificationViewController ()
@property (nonatomic, assign)NSInteger  index;
@end

@implementation NotificationViewController
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.tableArr = [NSMutableArray array];
        self.goodArr = [NSMutableArray array];
        self.index = 1;
    }
    return self;
}
//数组  或者只要是带有self 的初始化 都要在loadView里进行初始化
- (void)loadView
{
    [super loadView];
    [self createView];
    // 不能划出侧边栏
    YRSideViewController *slide = [YRSideViewController share];
    slide.needSwipeShowMenu = NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self requestData];
//    [self addheaderRefresh];
//    [self addFooterRefresh];
    [self buttonAction];
}
- (void)createView
{
    
    self.notiView = [[NotificationView alloc] initWithFrame:[UIScreen mainScreen].bounds];
//    [self.notiView createView];
    [self.notiView createViewHeaderView];
    self.view = self.notiView;
    
}
- (void)buttonAction
{
    [self.notiView.myHeaderView.backButton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.notiView.myHeaderView.editButton addTarget:self action:@selector(editButtonAction:) forControlEvents:UIControlEventTouchUpInside];
//    [self.notiView.myHeaderView.rightButton addTarget:self action:@selector(signRightAction:) forControlEvents:UIControlEventTouchUpInside];
    
}
//- (void)signRightAction:(id)sender
//{
//    
//}
- (void)backButtonAction:(id)sender
{
   [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)editButtonAction:(id)sender
{
    if (self.currentType == TableEditTypeNormal) {
        self.currentType = TableEditTypeDone;
        self.notiView.myHeaderView.editLable.text = @"完成";
        [ self.notiView.tableView setEditing:YES];
    } else {
        self.currentType = TableEditTypeNormal;
        self.notiView.myHeaderView.editLable.text = @"编辑";
        [self.notiView.tableView setEditing:NO];
    }
    [self.notiView.tableView reloadData];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 64;
}
//tableView的点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DetailModel *model = [self.tableArr objectAtIndex:indexPath.row];
    NSDictionary *other = [self.goodArr objectAtIndex:indexPath.row];
    
    NSString *urlStr = [NSString stringWithFormat:@"%@?infoId=%@", URL_SET_ALL_MSG_READED, model.id];
    [AFNetWorkingYU netWorkingHanderGetGataWithUrl:urlStr resultBlock:^(id result) {
        NSLog(@"%@", result);
        [self.tableArr removeObjectAtIndex:indexPath.row];
        [tableView reloadData];
}];

    
    DetailViewController *detailVC = [[DetailViewController alloc] init];
    detailVC.model = model;
    detailVC.otherDic = other;
    [self.navigationController pushViewController:detailVC animated:YES];
    
    //点击后标记消息已读 小红点闪烁取消
    [self LabelMessageRead:model.id];
}

#pragma mark - 这里标记消息已读（点击时）
- (void)LabelMessageRead:(NSString *)myId
{
    //设置单条消息已读  而不是所有
    NSString *getUrl = [NSString stringWithFormat:@"%@?infoId=%@", URL_SET_ALL_MSG_READED, myId];
    
    Reachability * reach = [Reachability reachabilityWithHostname:@"www.baidu.com"];
    if ([reach currentReachabilityStatus] != NotReachable) {

    [AFNetWorkingYU netWorkingHanderGetGataWithUrl:getUrl resultBlock:^(id result) {
        NSString *str = [result objectForKey:@"msg"];
        str = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSLog(@"回复： %@", str);
        
        //传送给服务器之后才跳转界面，此时应该插入一个动画 “正在同步服务器，请稍后”
        //[self.navigationController popViewControllerAnimated:YES];
        
    }];
    }
    else
    {
        //添加无网图
        UIView *fondView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
        [fondView setBackgroundColor:[UIColor whiteColor]];
        [self.view addSubview:fondView];
        [LoadIndicator networkStateNotReachableInView:fondView];

    }
    
    
}



- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}


///  提交修改tableview的方法
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    DetailModel *model = [self.tableArr objectAtIndex:indexPath.row];
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [self.tableArr removeObjectAtIndex:indexPath.row];
        NSString *urlStr = [NSString stringWithFormat:@"%@?infoId=%@", URL_SET_ALL_MSG_READED, model.id];
        Reachability * reach = [Reachability reachabilityWithHostname:@"www.baidu.com"];
        if ([reach currentReachabilityStatus] != NotReachable) {
        [AFNetWorkingYU netWorkingHanderGetGataWithUrl:urlStr resultBlock:^(id result) {
            NSLog(@"%@", result);
            [tableView reloadData];
        }];
        }
        else
        {
            //添加无网图
            UIView *fondView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
            [fondView setBackgroundColor:[UIColor whiteColor]];
            [self.view addSubview:fondView];
            [LoadIndicator networkStateNotReachableInView:fondView];
        }
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.tableArr count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    DetailModel *model = [self.tableArr objectAtIndex:indexPath.row];
    NotificationTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell1"];
    [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
    [cell.myPhoto setBackgroundColor: DIVIDINGLINECOLOR];
    cell.myTitle.text = model.title;
    cell.typeLable.text = [NSString stringWithFormat:@"%@ • ", model.category];
    NSString *imgStr = [NSString stringWithFormat:@"%@%@",@"http://www.isu.so/attached/u_img/",model.puberImg];
    [cell.myPhoto sd_setImageWithURL:[NSURL URLWithString:imgStr] placeholderImage:nil];
    return cell;
}

#pragma mark -
#pragma mark 数据
- (void)requestData
{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *userId = [user objectForKey:@"id"];
    NSString *approveKey= [GlobalMethod GetIOSUUID];
    NSString *deviceParam = [GlobalMethod getApproveKey];
    //&sort=pub_time&order=desc&rid=c45ca002-3e9c-459f-9e38-8befdffa5db0
    NSString *str =[NSString stringWithFormat:@"%@?approveKey=%@&devicePraram=%@&page=0&rows=20&sort=pub_time&rid=%@", URL_GET_MSG_INFO2,approveKey,deviceParam, userId];
    
    Reachability * reach = [Reachability reachabilityWithHostname:@"www.baidu.com"];
    if ([reach currentReachabilityStatus] != NotReachable) {

    [AFNetWorkingYU netWorkingHanderGetGataWithUrl:str resultBlock:^(id result) {
        if ([result isKindOfClass:[NSDictionary class]]) {
        NSDictionary *bigDic = (NSDictionary *)result;
        NSArray *array = [bigDic objectForKey:@"dataGrid"];
        for (NSDictionary *dic in array) {
            DetailModel *model = [[DetailModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            if (model.unreadMsg != 0) {
                
                [self.tableArr addObject:model];
            }
//            [self.tableArr addObject:model];
        }
        
        NSArray *goodArray = [bigDic objectForKey:@"other"];
        for (NSDictionary *myDic in goodArray) {
            NSDictionary *dic = [NSDictionary dictionaryWithDictionary:myDic];
            [self.goodArr addObject:dic];
        }
        if ([self.tableArr count] != 0) {
            [self.notiView createTableView];
            self.notiView.tableView.dataSource = self;
            self.notiView.tableView.delegate = self;
            [self.notiView.tableView registerClass:[NotificationTableViewCell class] forCellReuseIdentifier:@"cell1"];
            [self.notiView.tableView reloadData];
        } else {
            [self.notiView createNoData];
        }
        [self addFooterRefresh];
        [self addheaderRefresh];
        } else {
#warning <<<
        }
    }];
    }
    else
    {
        
        //添加无网图
        UIView *fondView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
        [fondView setBackgroundColor:[UIColor whiteColor]];
        [self.view addSubview:fondView];
        [LoadIndicator networkStateNotReachableInView:fondView];

    }
}
- (void)addheaderRefresh
{
//    [self.tableArr removeAllObjects];
    [self.notiView.tableView addHeaderWithCallback:^{
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        NSString *userId = [user objectForKey:@"id"];
        NSString *device = [GlobalMethod getApproveKey];
        NSString *key = [GlobalMethod GetIOSUUID];
        NSString *str =[NSString stringWithFormat:@"approveKey=%@&devicePraram=%@&page=0&rows=20&sort=remsg_time&rid=%@",key,device, userId];
        
        Reachability * reach = [Reachability reachabilityWithHostname:@"www.baidu.com"];
        if ([reach currentReachabilityStatus] != NotReachable) {

        [AFNetWorkingYU netWorkWithURL:URL_GET_INFO_LIST body:str resultBlock:^(id result) {
            NSDictionary *bigDic = (NSDictionary *)result;
            NSArray *array = [bigDic objectForKey:@"rows"];
            for (NSDictionary *dic in array) {
                DetailModel *model = [[DetailModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                if (model.unreadMsg != 0) {
                    [self.tableArr addObject:model];
                }
                //            [self.tableArr addObject:model];
            }
        }];
        }
        else
        {
            //添加无网图
            UIView *fondView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
            [fondView setBackgroundColor:[UIColor whiteColor]];
            [self.view addSubview:fondView];
            [LoadIndicator networkStateNotReachableInView:fondView];

        }
        [self.notiView.tableView reloadData];
        [self.notiView.tableView headerEndRefreshing];
    }];
    
     
}
- (void)addFooterRefresh
{
    
    if (self.index < 10) {
        [self.notiView.tableView addFooterWithCallback:^{
            NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
            NSString *userId = [user objectForKey:@"id"];
            NSString *device = [GlobalMethod getApproveKey];
            NSString *key = [GlobalMethod GetIOSUUID];
            //&sort=pub_time&order=desc&rid=c45ca002-3e9c-459f-9e38-8befdffa5db0
            NSString *str =[NSString stringWithFormat:@"approveKey=%@&devicePraram=%@&page=%ld&rows=20&sort=remsg_time&rid=%@",key,device,self.index, userId];
//            [AFNetWorkingYU netWorkWithURL:URL_GET_INFO_LIST body:str resultBlock:^(id result)
            Reachability * reach = [Reachability reachabilityWithHostname:@"www.baidu.com"];
            if ([reach currentReachabilityStatus] != NotReachable) {

            [AFNetWorkingYU netWorkingHanderGetGataWithUrl:str resultBlock:^(id result) {
                if ([result isKindOfClass:[NSDictionary class]]) {
                NSDictionary *bigDic = (NSDictionary *)result;
                NSArray *array = [bigDic objectForKey:@"rows"];
                for (NSDictionary *dic in array) {
                    DetailModel *model = [[DetailModel alloc] init];
                    [model setValuesForKeysWithDictionary:dic];
                    if (model.unreadMsg == -1) {
                        
                        [self.tableArr addObject:model];
                    }
                    //            [self.tableArr addObject:model];
                }
                } else {
#warning <<< //添加无网图
                    UIView *fondView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
                    [fondView setBackgroundColor:[UIColor whiteColor]];
                    [self.view addSubview:fondView];
                    [LoadIndicator networkStateNotReachableInView:fondView];

                }
            }];
            }
            else
            {
                UIView *fondView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
                [fondView setBackgroundColor:[UIColor whiteColor]];
                [self.view addSubview:fondView];
                [LoadIndicator networkStateNotReachableInView:fondView];
                
            }
            [self.notiView.tableView reloadData];
            [self.notiView.tableView footerEndRefreshing];
        }];
        self.index++;
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
